export default function createStore(reducer, initState, rewriteCreateStoreFunc) {
  if (typeof initState === 'function' && typeof rewriteCreateStoreFunc === 'undefined') {
    rewriteCreateStoreFunc = initState;
    initState = undefined;
  }

  if (rewriteCreateStoreFunc) {
    const newCreateStore = rewriteCreateStoreFunc(createStore)
    return newCreateStore(reducer, initState)
  }

  let state = initState
  let listeners = []

  function replaceReducer(nextReducer) {
    reducer = nextReducer
    /* 刷新state , 新的reducer 加入状态树中 */
    dispatch({ type: Symbol() })
  }

  function subscribe(listener) { // 订阅
    listeners.push(listener)
    return function unsubscribe() { // 退订
      const index = listeners.indexOf(listener)
      listeners.splice(index, 1)
    }
  }

  function dispatch(action) {
    /* 按派遣计划改变 state */
    state = reducer(state, action)
    for(let i=0;i<listeners.length;i++) {
      const listener = listeners[i]
      listener()
    }
  }

  function getState() {
    return state
  }

  dispatch({ type: Symbol() }) // 为状态 赋初值

  return {
    subscribe, dispatch, getState, replaceReducer
  }
}